import { gameHelper } from "../../Utils/GameHelpler";

const { ccclass, property, menu, executeInEditMode } = cc._decorator;

@ccclass
@executeInEditMode
@menu('cccframework/' + ItemPosBind.name)
export default class ItemPosBind extends cc.Component {

    @property([cc.Node])
    bindNodes: cc.Node[] = [];
    @property
    isAjust: boolean = false;
    @property
    _relativePosList: cc.Vec2[] = [];
    @property({ type: [cc.Vec2] })
    get relativePosList(): cc.Vec2[] {
        if (CC_EDITOR && this.isAjust) {
            let bindNodes = this.bindNodes.filter(v => { return v && v.isValid })
            let relativePosList = [];
            if (bindNodes.length) {
                for (let i = 0; i < bindNodes.length; i++) {
                    let bindNode = bindNodes[i];
                    relativePosList.push(
                        gameHelper.getWpos(bindNode).sub(gameHelper.getWpos(this.node))
                    )
                }
            }
            this._relativePosList = relativePosList;
        }
        return this._relativePosList;
    }

    onLoad() {
        this.node.on(cc.Node.EventType.POSITION_CHANGED, this.moveTogether, this)
    }

    moveTogether() {
        let bindNodes = this.bindNodes.filter(v => { return v && v.isValid })
        let relativePosList = this.relativePosList;
        // debugger
        bindNodes.forEach((v, i) => {
            v.position = this.node.position.add(relativePosList[i])
        })
    }
    update() {
        // this.moveTogether()
    }

}
